package com.itheima.proxy_review.cglib;

import com.itheima.proxy_review.jdk.Service1Impl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: design
 * @description: cglib代理
 * 1:用Enhandler来啦
 * 2:通过代理对象执行
 * @author: zhanghz001
 * @create: 2021-02-26 22:28
 **/
public class CGLibProxyTest {
    
    public static void main(String[] args) {
        //不能是final修饰,不需要接口,需要创建类的实例,代理的是类,不是接口
        Service1Impl instance = new Service1Impl();
        
        //创建代理类
        MethodInterceptor proxy = new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method,
                                    Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("代理前面操作");
                Object invoke = method.invoke(instance, objects);
                System.out.println("代理后面操作");
                return invoke;
            }
        };
        
        //不用接口也可以,只要不是final修饰就行
        Service1Impl o = (Service1Impl) Enhancer.create(Service1Impl.class,
                Service1Impl.class.getInterfaces(), proxy);
        o.pay("hahaha");
    }
    
    //final修饰是不可以代理的
    public static void main0(String[] args) {
        String s1 = "";
        String o = (String) Enhancer.create(String.class, new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if (method.getName().equals("toString")) {
                    System.out.println("toString来了");
                }
                return method.invoke(s1, objects);
            }
        });
        o.toString();
    }
    
}
